import { message } from "antd";
import moment, { Moment } from "moment";
import { Reducer } from "react";
import { Action, combineReducers } from "redux";
import { BudgetExhibit } from "../../interface/budgetData";
import { DataRowResult } from "../../interface/response";
import { BudgetListReducer } from "../BudgetList/budget-list-reducer";
import { ActionProps } from "../type";
import { BudgetDataActionEnum, DarkModeActionEnum, FilterDateActionEnum } from "./type";

const DarkModeReducer: Reducer<boolean, Action<DarkModeActionEnum>> = (state: boolean = false, actions: Action<DarkModeActionEnum>): boolean =>
{
    if (actions.type === DarkModeActionEnum.Dark) state = true;
    if (actions.type === DarkModeActionEnum.Light) state = false;
    return state;
};

const BudgetDataReducer: Reducer<Object, ActionProps<BudgetDataActionEnum, Object>> =
    (state: Object = {}, action: ActionProps<BudgetDataActionEnum, Object>): Object =>
    {
        switch (action.type)
        {
            case BudgetDataActionEnum.Select:
                state = (action.payload as BudgetExhibit[]);
                return state;
            case BudgetDataActionEnum.Update:
                if ((action.payload as DataRowResult).affectedRows === 1)
                {
                    message.success("更新成功");
                } else
                {
                    message.error('更新失败');
                }
                return state;
            default:
                return state;
        }
    };

const FilterDateReducer: Reducer<Moment[], ActionProps<FilterDateActionEnum, Moment[]>> =
    (state: Moment[] = [moment().startOf('month'), moment().endOf('month')], action: ActionProps<FilterDateActionEnum, Moment[]>): Moment[] =>
    {
        if (action.type === FilterDateActionEnum.GetFilterDate)
        {
            return state;
        }
        if (action.type === FilterDateActionEnum.SetFilterDate)
        {
            state = action.payload;
        }
        return state;
    };


export const RootReducer = combineReducers({
    DarkModeReducer,
    BudgetDataReducer,
    FilterDateReducer,
    BudgetListReducer,
});
